package pay

import (
	"fmt"
	"github.com/name5566/leaf/log"
	"github.com/pkg/errors"
	"talent.com/agency_im/common/msg"
	"talent.com/agency_im/common/platform"
	"talent.com/agency_im/common/user"
	"talent.com/agency_im/conf"
	"time"
)

func GetAgencyPayTypes(playerID uint64, agencyID uint64) (*[] PayType, error) {
	var (
		err            error
		agency         *user.User
		player         *user.User
		playerPlatform *platform.Platform
		payTypes       *[]PayType
	)
	if agency, err = convertAgency(agencyID); err != nil {
		return nil, err
	}

	if player, playerPlatform, err = convertPlay(playerID); err != nil {
		return nil, err
	}

	if payTypes, err = getAgencyPayTypes(agency.ThirdUserID, playerPlatform.PayMchID, player.ThirdUserID); err != nil {
		return nil, err
	}

	return payTypes, nil
}

func GetAgencyReceiptAddress(playerID uint64, agencyID uint64, payType PayType, byAgency bool) (*ReceiptAddress, error) {
	var (
		err            error
		agency         *user.User
		player         *user.User
		playerPlatform *platform.Platform
		receipt        *ReceiptAddress
	)
	if agency, err = convertAgency(agencyID); err != nil {
		return nil, err
	}

	if player, playerPlatform, err = convertPlay(playerID); err != nil {
		return nil, err
	}

	if receipt, err = getAgencyReceiptAddressByPayType(agency.ThirdUserID, playerPlatform.PayMchID, player.ThirdUserID, payType, byAgency); err != nil {
		return nil, err
	} else {
		return receipt, nil
	}

}

// 启动一个私聊会话时，获取问候语
// 只有首次进入会话才会发送问候语
func GetAgencyGreeting(playerID uint64, agencyID uint64) (greeting string, err error) {
	// 首次会话（之前没有过聊天记录）
	var (
		existedTopic bool
		agency       *user.User
		agencyInfo   *AgencyInfo
	)

	if existedTopic, err = msg.HasExistPrivateTopic(playerID, agencyID); existedTopic || err != nil {
		return
	}

	if agency, err = convertAgency(agencyID); err != nil {
		return
	}

	if agency.PlatformID != conf.ServerConfig().Pay.AgencyPlatformID {
		return
	}

	// first get from cache
	if cv, found := Cache.Get(fmt.Sprintf(CacheKeyAgencyInfo, agencyID)); found {
		log.Debug("get agency info from cache")
		agencyInfo = cv.(*AgencyInfo)
	} else {
		if agencyInfo, err = getAgencyInfo(agency.ThirdUserID); err != nil {
			return
		} else {
			// set cache
			Cache.Set(fmt.Sprintf(CacheKeyAgencyInfo, agencyID), agencyInfo, 10*time.Minute)
		}
	}
	if agencyInfo.Prologue == "" {
		agencyInfo.Prologue = "亲，您好，下方按钮是目前可用充值方式，请点选您需要的充值方式。"
	}
	return agencyInfo.Prologue, nil

}

func CreatePayOrder(playerID uint64, agencyID uint64, amount int64, receiptAddressID int, payType PayType) (*RechargeOrder, error) {
	var (
		err            error
		agency         *user.User
		player         *user.User
		playerPlatform *platform.Platform
		payOrder       *RechargeOrder
	)
	if agency, err = convertAgency(agencyID); err != nil {
		return nil, err
	}

	if player, playerPlatform, err = convertPlay(playerID); err != nil {
		return nil, err
	}
	if payOrder, err = createPayOrder(agency.ThirdUserID, playerPlatform.PayMchID, player.ThirdUserID, amount, "127.0.0.1", receiptAddressID, payType); err != nil {
		return nil, err
	} else {
		return payOrder, nil
	}
}

func MakeAgencyOffWork(UserID uint64) (bool, error) {
	var (
		err error
		u   *user.User
	)
	if u, err = convertAgency(UserID); err != nil {
		return false, err
	}

	return makeAgentOffWork(u.ThirdUserID)
}

// 获取商户玩家的用户信息
func GetPlayerInfo(playerID uint64, agencyID uint64) (*PlayerInfo, error) {
	var (
		err            error
		agency         *user.User
		player         *user.User
		playerPlatform *platform.Platform
		playerInfo     *PlayerInfo
	)
	if agency, err = convertAgency(agencyID); err != nil {
		return nil, err
	}

	if player, playerPlatform, err = convertPlay(playerID); err != nil {
		return nil, err
	}

	if playerInfo, err = getPlayerInfo(playerPlatform.PayMchID, player.ThirdUserID, agency.ThirdUserID); err != nil {
		return nil, err
	} else {
		return playerInfo, nil
	}

}

// 获取代理快捷回复
func GetUserQuickReply(userID uint64) (*[]QuickReply, error) {
	var (
		err        error
		agency     *user.User
		quickReply *[]QuickReply
	)
	if agency, err = convertAgency(userID); err != nil {
		return nil, err
	}

	if quickReply, err = getAgencyQuickReply(agency.ThirdUserID); err != nil {
		return nil, err
	} else {
		return quickReply, nil
	}

}

func AddBlacklist(agencyID uint64, playerID uint64, remark string) error {
	var (
		err            error
		agency         *user.User
		player         *user.User
		playerPlatform *platform.Platform
	)
	if agency, err = convertAgency(agencyID); err != nil {
		return err
	}

	if player, playerPlatform, err = convertPlay(playerID); err != nil {
		return err
	}
	return addBlacklist(agency.ThirdUserID, playerPlatform.PayMchID, player.ThirdUserID, remark)
}

func IsBlacklist(agencyID uint64, playerID uint64) (bool, error) {
	var (
		err            error
		agency         *user.User
		player         *user.User
		playerPlatform *platform.Platform
		result         bool
	)
	if agency, err = convertAgency(agencyID); err != nil {
		return false, err
	}

	if player, playerPlatform, err = convertPlay(playerID); err != nil {
		return false, err
	}

	if result, err = isBlacklist(agency.ThirdUserID, playerPlatform.PayMchID, player.ThirdUserID); err != nil {
		return false, err
	} else {
		return result, nil

	}
}

// 获取商户玩家的用户信息
func ComplainUser(SourceID uint64, TargetID uint64, Content string, ComplainTypes uint64, Images []string) (*ComplainResp, error) {
	var (
		err    error
		u      *user.User
		p      *platform.Platform
		agency *user.User
		result *ComplainResp
	)

	if agency, err = convertAgency(TargetID); err != nil {
		return nil, err
	}

	if u, err = user.GetUser(SourceID); err != nil {
		return nil, err
	}

	if p, err = platform.GetPlatformByID(u.PlatformID); err != nil {
		return nil, err
	}

	if result, err = complainAgency(u.ThirdUserID, p.PayMchID, agency.ThirdUserID, ComplainTypes, Images, Content); err != nil {
		return nil, err
	} else {
		return result, nil
	}

}

func convertAgency(userID uint64) (*user.User, error) {
	ag, err := user.GetUser(userID)
	if err != nil {
		return nil, err
	}
	if ag.PlatformID != conf.ServerConfig().Pay.AgencyPlatformID {
		//return nil, errors.Errorf("user is not agency of pay: %v", userID)
	}
	return ag, nil
}

func convertPlay(userID uint64) (*user.User, *platform.Platform, error) {
	player, err := user.GetUser(userID)
	if err != nil {
		return nil, nil, err
	}
	if player.PlatformID == conf.ServerConfig().Pay.AgencyPlatformID {
		return nil, nil, errors.Errorf("user must not be agency: %v", userID)
	}
	pt, err := platform.GetPlatformByID(player.PlatformID)
	if err != nil {
		return nil, nil, err
	}
	return player, pt, nil
}
